from threading import Thread
import time

class thread_file_download(Thread):
    def __init__(self,url,startpos,endpos,f,s,sema):
        super(thread_file_download,self).__init__()
        self.url = url
        self.startpos = startpos
        self.endpos = endpos
        self.fd = f
        self.s = s
        self.sema = sema
    def download(self):
        headers = {"Range":"bytes=%s-%s"%(self.startpos,self.endpos)}
        for i in range(5):
            try:
                res = self.s.get(self.url,headers=headers)
                break
            except:
                print('多线程下载失败','8秒后开始','第',(i+1),'尝试')
                time.sleep(8)
        # res.text 是将get获取的byte类型数据自动编码，是str类型， res.content是原始的byte类型数据
        # 所以下面是直接write(res.content)
        self.fd.seek(self.startpos)
        self.fd.write(res.content)
        # f.close()
    def run(self):
        with self.sema:
            self.download()